process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var config = require('./config');
var mongoose = require('mongoose');

var app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// 连接MongoDB数据库
mongoose.connect(config.mongo.uri, config.mongo.options);

/*路由引用*/
require('./routes')(app);

//设置跨域访问
app.all('/api/*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods","*");
    res.header("Access-Control-Max-Age", "60");
    next();
});


// 处理404错误
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// 开发模式错误处理
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.json(err);
    });
}

// 生产模式错误处理
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.json(err);
});

module.exports = app;
